package day14;

import java.io.*;
import java.util.Scanner;

/**
 * 文件拷贝：
 *  1.提示输入源文件路径。
 *  2.要求指定复制到的目录，如果目录不存在，自动创建
 *  3.文件名，如果没有则默认原文件名，如果冲突，自动命名，规则自定
 * Created by kunsb on 2016/11/1.
 */
public class Copy {
    public static void main(String[] args) {
        System.out.println("请输入源文件路径：");
        Scanner scanner = new Scanner(System.in);
        String read =scanner.nextLine();
        File file = new File(read);
        if (!file.exists()) {
            System.out.println("文件不存在！");
            return;
        }
        System.out.println("请输入复制到的文件路径：");
        String road = scanner.nextLine();
        File path =new File(road);
        if (!path.exists()){
            path.mkdirs();//创建该路径中所有不存在的文件夹
        }
        System.out.println("请输入文件名：");
        String newName = scanner.nextLine();
        if (newName == null || "".equals(newName)) {
            newName = file.getName();
        }
        File target = new File(road + "\\" + newName);
        int i = 1;
        while (target.exists()){
            String[] split = newName.split("\\.");
            target = new File(road + "\\" + split[0] + i + "." + split[1]);
            i++;
        }
        FileInputStream bili = null;
        FileOutputStream out = null;
        long start = System.currentTimeMillis();
        try {
            out = new FileOutputStream(target);
            bili = new FileInputStream(file);
            /*byte[] bis = new byte[1024*10];
            int bi;
            while ((bi = bili.read(bis)) != -1)
                out.write(bis);*/
            int bi;
            while ((bi = bili.read()) != -1)
                out.write(bi);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bili.close();
                out.close();
            } catch (IOException e) {
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("复制耗时" + (end - start) + "ms");
    }
}
